<template>
  <div class="role-management">
    <!-- 左侧面板：角色列表（目录） -->
    <div class="left-panel">
      <el-tabs v-model="activeLeftTab">
        <el-button @click="addRole" type="primary">新增角色</el-button>
        <el-tab-pane label="角色列表" name="role">
          <ul>
            <li
              v-for="role in roles"
              :key="role.id"
              :class="{ selected: role.id === selectedRole.id }"
              @click="selectRole(role)"
            >
              <div class="role-item">
                <span class="role-name">{{ role.name }}</span>
                <!-- 角色名称 -->
                <div class="action-buttons">
                  <!-- 操作按钮 -->
                  <el-button
                    @click.stop="viewRole(role)"
                    type="text"
                    size="mini"
                    >查看</el-button
                  >
                  <el-button
                    v-if="canModify(role)"
                    @click.stop="modifyRole(role)"
                    type="text"
                    size="mini"
                    >修改</el-button
                  >
                  <el-button
                    v-if="canDelete(role)"
                    @click.stop="deleteRole(role.id)"
                    type="text"
                    size="mini"
                    >删除</el-button
                  >
                </div>
              </div>
            </li>
          </ul>
        </el-tab-pane>
      </el-tabs>
      <el-dialog width="35%" :visible.sync="dialogRoleVisible">
        <el-form>
          <el-form-item label="角色名称" required>
            <el-input v-model="role.name"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            @click="dialogRoleVisible = false"
            v-if="this.dialogType !== 'view'"
            >取消</el-button
          >
          <el-button
            type="primary"
            @click="saveRole"
            v-if="this.dialogType !== 'view'"
            >保存</el-button
          >
        </div>
      </el-dialog>
    </div>

    <!-- 右侧面板：用户和权限选项卡 -->
    <div class="right-panel">
      <!-- 选项卡切换 -->
      <el-tabs v-model="activeRightTab">
        <el-tab-pane label="用户" name="user">
          <el-button @click="addUser" type="primary">新增用户</el-button>
          <!-- 新增按钮放在这里 -->
          <el-table :data="rolebyUsers">
            <el-table-column prop="name" label="用户名"></el-table-column>
            <el-table-column prop="userName" label="账号"></el-table-column>
            <el-table-column
              prop="phoneNumber"
              label="手机号码"
            ></el-table-column>
            <el-table-column prop="isActive" label="状态">
              <template slot-scope="scope">
                {{ scope.row.isActive ? "启用" : "禁用" }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="removeUser(scope.row.id)"
                  type="danger"
                  size="mini"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="权限" name="permission">
          <el-tree
            :data="treeData"
            show-checkbox
            node-key="code"
            :default-checked-keys="defaultCheckedKeys"
            ref="tree"
          >
          </el-tree>
          <el-button
            @click="savepermission"
            style="margin-top: 10px"
            type="primary"
            >保存</el-button
          >
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-dialog width="35%" :visible.sync="dialogTransferVisible">
      <el-transfer
        v-model="selectUsers"
        filterable
        :data="allUsers"
        :titles="['用户列表', '角色用户']"
      ></el-transfer>
      <div class="button-container">
        <el-button @click="addUser" type="primary">确定</el-button>
        <el-button @click="dialogTransferVisible = false" type="primary"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTreeMenus } from "@/api/menu";
import { getPermssion } from "@/api/permission";
import {
  getRoles,
  addRole,
  deleteRole,
  updateRole,
  getUserbyId,
} from "@/api/role";
import { getUserByPaged } from "@/api/user";
export default {
  data() {
    const generateData = (_) => {
      const data = [];
      for (let i = 1; i <= 15; i++) {
        data.push({
          key: i,
          label: `备选项 ${i}`,
          disabled: i % 4 === 0,
        });
      }
      return data;
    };
    return {
      data: generateData(),
      dialogTransferVisible: false,
      dialogRoleVisible: false,
      rolename: "",
      rolebyUsers: [],
      dialogType: "",
      value: [1, 4],
      selectUsers: [],
      activeLeftTab: "role",
      activeRightTab: "user", // 默认选中的选项卡
      treeData: [],
      where: {},
      defaultCheckedKeys: [],
      role: {
        name: "",
        id: "",
      },
      roles: [],
      allUsers: [],
      selectedRole: {}, // 选中的角色
    };
  },
  mounted() {},
  async created() {
    await this.getRoles();
    await this.loadGetUserByPaged();
    this.loadTreeMenus();
  },
  methods: {
    async getRoles() {
      const res = await getRoles();
      this.roles = res.data.items;
      if (this.roles.length > 0) {
        this.selectedRole = this.roles[0]; // 在页面加载时选中第一个角色
        this.getrolePermission(this.selectedRole.name);
        await this.getUserByRoleId(this.selectedRole.id);
      }
    },
    async loadGetUserByPaged() {
      const data = {
        SkipCount: 1,
        MaxResultCount: 2000,
      };
      const res = await getUserByPaged(data);
      this.allUsers = this.transformedUseritem(res.items);
      this.trackSelectUsers();
    },
    trackSelectUsers(){
      const roleUserIds = this.rolebyUsers.map(user => user.id);
      this.selectUsers=[]; //先清空
      debugger;
      this.allUsers.forEach((user) => {
        if (roleUserIds.includes(user.id)) {
          this.selectUsers.push(user.id);
        }
      });
    },
    savepermission() {
      const checkedKeys = this.$refs.tree.getCheckedKeys();
      console.log("Default Checked Keys:", this.defaultCheckedKeys);
      console.log("Checked Keys:", checkedKeys);

      const areArraysEqual =
        checkedKeys.length === this.defaultCheckedKeys.length &&
        checkedKeys.every((key) => this.defaultCheckedKeys.includes(key));

      if (areArraysEqual) {
        console.log("No changes, not calling the API.");
      } else {
        console.log("There are changes, calling the API...");
        // 在这里调用您的 API
      }
    },
    async saveRole() {
      const isEdit = this.dialogType === "edit";
      if (this.role.name === "") {
        this.$message.error("请输入角色名称");
        return;
      }
      if (isEdit) {
        const res = await updateRole(this.role.id, this.role);
        if (res.code === 1) {
          for (let index = 0; index < this.roles.length; index++) {
            if (this.roles[index].id === this.role.id) {
              this.roles.splice(index, 1, Object.assign({}, this.role));
              break;
            }
          }
        }
        this.$message({
          message: "修改成功",
          type: "success",
        });
        this.dialogRoleVisible = false;
      } else {
        const data = {
          name: this.role.name,
        };
        const res = await addRole(data);
        this.roles.push(res.data);
        this.$message({
          message: "新增角色成功",
          type: "success",
        });
        this.dialogRoleVisible = false;
      }
    },
    modifyRole(role) {
      // 实现修改角色的逻辑
      console.log("Modify Role", role);
      this.dialogType = "edit";
      this.dialogRoleVisible = true;
      this.role = role;
    },
    addRole() {
      this.dialogRoleVisible = true;
      this.dialogType = "add";
    },
    addUser() {
      this.dialogTransferVisible = true;
    },
   async getUserByRoleId(roleId) {
    this.rolebyUsers= await getUserbyId(roleId);
    },
    getrolePermission(rolename) {
      getPermssion("R", rolename)
        .then((res) => {
          const permissionsGroups = res.groups;
          let allPermissions = [];
          permissionsGroups.forEach((element) => {
            element.permissions.forEach((item) => {
              if (item.isGranted === true) {
                allPermissions.push(item.name);
              }
            });
          });
          this.$refs.tree.setCheckedKeys([]);
          this.defaultCheckedKeys = []; // 清空 defaultCheckedKeys
          this.checkPermissions(this.treeData, allPermissions);
        })
        .catch((error) => {
          this.$message.error(error.toString());
        });
    },
    checkPermissions(treeData, allPermissions) {
      treeData.forEach((node) => {
        // 检查当前节点的 code 是否存在于 allPermissions 中
        if (allPermissions.includes(node.code)) {
          // 如果存在，则将该节点的 key 加入到 defaultCheckedKeys 数组中
          this.defaultCheckedKeys.push(node.code);
        }
        // 如果当前节点有子节点，递归遍历子节点
        if (node.children && node.children.length > 0) {
          this.checkPermissions(node.children, allPermissions);
        }
      });
    },

    viewRole(role) {
      this.role = role;
      // 实现查看角色的逻辑
      this.dialogType = "view";
      this.dialogRoleVisible = true;
    },
    async deleteRole(roleId) {
      this.$confirm("确认移除角色?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await deleteRole(roleId);
          var index = this.roles.findIndex((x) => x.id == roleId);
          if (index != -1) {
            this.roles.splice(index, 1);
          }
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
   async selectRole(role) {
      // 处理角色选中事件
      this.selectedRole = role;
      this.getrolePermission(this.selectedRole.name);
      await this.getUserByRoleId(this.selectedRole.id);
      this.trackSelectUsers();
    },
    canModify(role) {
      // 如果是系统角色则不能修改，否则可以修改
      return !role.isStatic;
    },
    canDelete(role) {
      // 如果是系统角色则不能删除，否则可以删除
      return !role.isStatic;
    },
    loadTreeMenus() {
      getTreeMenus(this.where)
        .then((res) => {
          this.treeData = this.transformTreeData(res);
        })
        .catch((error) => {
          this.$message.error(error);
        });
    },
    removeUser(id) {},
    transformedUseritem(users) {
     return users.map((item) => {
        let transformedItem = {
          id:item.id,
          key: item.id,
          label: item.name,
          disabled: !item.isActive,
        };
        return transformedItem;
      });
    },
    transformTreeData(originalData) {
      return originalData.map((item) => {
        let transformedItem = {
          key: item.id,
          id: item.id,
          label: item.name,
          code: item.code,
          icon: item.meta?.icon,
          data: item.menuType,
        };
        if (item.children && item.children.length > 0) {
          transformedItem.children = this.transformTreeData(item.children);
        }
        return transformedItem;
      });
    },
  },
};
</script>

<style scoped>
.button-container {
  display: flex;
  justify-content: center;
  margin-top: 20px; /* Adjust the margin as needed */
}

.button-container .el-button {
  margin: 0 10px; /* Adjust the margin between the buttons as needed */
}
/* 样式可以根据需要自定义 */
.role-item {
  display: flex;
  align-items: center; /* 使角色名称和操作按钮在同一水平线上 */
}

.role-name {
  flex-grow: 1; /* 角色名称占据剩余空间 */
}

.action-buttons {
  margin-left: 10px;
  display: flex;
  justify-content: space-between; /* 确保按钮之间有均匀的空间 */
}

.action-buttons > .el-button {
  margin-right: 5px; /* 为每个按钮设置右边距，您可以根据需要调整这个值 */
}

.action-buttons > .el-button:last-child {
  margin-right: 0; /* 确保最后一个按钮没有右边距 */
}
.role-management {
  display: flex;
  width: 80%;
  margin: 10px 20px 20px 20px;
  border: 1px solid #f0f0f0; /* 添加边框 */
  border-radius: 10px; /* 设置边框圆角 */
}
.selected {
  background-color: rgb(235, 241, 255); /* 使用 RGB 值设置背景色 */
  border-radius: 5px; /* 设置边框圆角 */
  cursor: pointer; /* 设置鼠标悬停时的光标样式 */
}
.left-panel {
  width: 30%; /* 左侧面板占据 30% 的宽度 */
  padding: 20px;
  border-right: 1px solid #f0f0f0; /* 在left-panel的右侧添加一条灰色的线 */
}

.right-panel {
  flex: 1; /* 右侧面板占据剩余的宽度 */
  padding: 20px;
}

/* 角色列表项样式 */
.left-panel ul {
  list-style: none;
  padding: 0;
  cursor: pointer;
  padding: 0 20px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  height: 20px;
  line-height: 20px;
  display: inline-block;
  list-style: none;
  font-size: 14px;
}

.left-panel ul li {
  margin-bottom: 10px;
}

/* 选项卡样式 */
.el-tabs__nav {
  background-color: #f0f0f0;
}
</style>
